package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 生成Redis唯一Id
 */
@Component
public class RedisIdWorker {
    //到今年第一天的秒数
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    //序列号的位数
    private static final long COUNT_TIMESTAMP = 32L;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix){//不同业务

        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);   //当前秒数
        long timeStamp = nowSecond-BEGIN_TIMESTAMP;             //相对秒数

        //生成序列号
        //获取当前日期
        String today = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //设置为自增长，默认一次加一，得到序列号
        long count = stringRedisTemplate.opsForValue().increment("irc:" + keyPrefix + ":" + today);

        //位运算拼接
        return timeStamp << COUNT_TIMESTAMP  |  count ;
    }

}
